/**
 *	@project:	kybernetes
 *	@author:	D.Toepel
 *	@note:		---
 *	
 *	Copyright (C) 2009  D.Toepel <de.dtools> {at} <gmail> {dot} <com>
 *	
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *	
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *	
 *	You should have received a copy of the GNU General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *	
 */
package dt.htwk.rmi;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketPermission;
import java.net.SocketTimeoutException;

import dt.htwk.core.KCStatusBar;

/**
 * <h3>BroadCastClient</h3>
 * 
 * @author DToepel
 * 
 */
public class BroadCastClient extends Thread {

/* ****************************************************
 * Deklaration der Variablen und Komponenten
 * ***************************************************/

	/**
	 * serialVersionUID -- Standard: 1L
	 */
	private static final long serialVersionUID = 1L;

	private static final int BCPORT = 15177;

/* ****************************************************
 * Aufruf des Konstruktors
 * ***************************************************/
	

/* ****************************************************
 * PUBLIC - oeffentliche Methoden
 * ***************************************************/

	public void run() {
		DatagramSocket udpSocket = null;
		try {
			udpSocket = new DatagramSocket(BCPORT);
			udpSocket.setBroadcast(true);
			udpSocket.setSoTimeout(5000);
			
			byte[] buffer = new byte[1024];
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			udpSocket.receive(packet);
			
			String msg = new String(packet.getData(), 0, packet.getLength());

			if (msg.equals("KCServer")) {
				
				System.out.print("Antwort von "
						+ packet.getAddress().getHostAddress() + ":");
				System.out.println(msg);

				RMIClient.setServerAddress(packet.getAddress().getHostAddress());
				if (RMIClient.Connect2Server()) {
					KCStatusBar.setDisconnectedA();
				}
			}
			udpSocket.close();
			udpSocket.disconnect();
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/* ****************************************************
	 * PRIVATE - nicht-oeffentliche Methoden
	 * **************************************************
	 */

}
